import { Injectable } from '@nestjs/common';
import ActionResult, {
  ActionResultTemplateInterface,
} from './../common/ResponseResult';
import { queryPgDatabases, insertPgDatabases } from '../service/dataSource';
import { makeSalt, encryptPassword } from './../utils/cryptogram';
@Injectable()
export default class TestDaoImpl {
  /**
   * 查询某个用户是否存在
   * @param userName 用户名
   * @returns
   */
  async queryUser(userName: string): Promise<ActionResultTemplateInterface> {
    return await queryPgDatabases({
      sql: `select * from life_notes.admin_user where user_name = $1`,
      params: [userName],
    });
  }
  /**
   * 注册用户
   * @param userName 用户名
   * @returns
   */
  async registerUser(
    userName: string,
    userRealName: string,
    userPassword: string,
    rePassword: string,
    userMobile: string,
  ): Promise<ActionResultTemplateInterface> {
    if (userPassword !== rePassword) {
      return ActionResult.success({ message: '两次密码输入不一致', data: [] });
    }
    const users = await (await this.queryUser(userName)).data;
    console.log('users:');
    console.log(users);
    const isHaveUser = users.filter((item) => item.user_name === userName);
    if (isHaveUser.length > 0) {
      return ActionResult.success({ message: '用户已存在', data: [] });
    }
    const salt = makeSalt(); // 制作密码盐
    const hashPwd = encryptPassword(userPassword, salt); // 加密密码
    return await insertPgDatabases({
      sql: `insert into life_notes.admin_user
      (user_id, user_name, user_real_name, user_passwd, passwd_salt,
        user_mobile, user_status, user_role)
      values
      ($1,$2,$3,$4,$5,$6,$7,$8)`,
      params: [3, userName, userRealName, hashPwd, salt, userMobile, 1, 3],
      // params: [],
    });
  }
}
